# -*- coding:utf-8 -*-
# !/usr/bin/env python
"""
Date: 2025/3/11 17:00
Desc: 东方财富网-数据中心-特色数据-期权价值分析
https://data.eastmoney.com/other/valueAnal.html
"""

import pandas as pd
import time

from func import fetch_paginated_data


def option_value_analysis_em(exchange:str ='SSE') -> pd.DataFrame:
    """
    东方财富网-数据中心-特色数据-期权价值分析
    https://data.eastmoney.com/other/valueAnal.html
    :exchange: 交易所 SSE(上交所) 和 SZSE（深交所）
    :return: 期权价值分析
    :rtype: pandas.DataFrame
    """
    url = "https://push2.eastmoney.com/api/qt/clist/get"
    # 定义交易所代码映射
    fs_map = {"SSE": "A10", "SZSE": "A12"}

    # 检查交易所参数是否合法
    if exchange not in fs_map:
        raise ValueError(f"不支持的交易所: {exchange}，请使用'SSE'或'SZSE'")

    timestamp_ms = int(time.time() * 1000)  # 毫秒级时间戳
    timestamp_ms_str = str(timestamp_ms)

    # 构建请求参数
    params = {
        # "cb":f"jQuery112302677364063236233_{timestamp_ms_str}",
        "fid": "f301",
        "po": "1",
        "pz": "50",
        "pn": "1",
        "np": "1",
        "fltt": "2",
        "invt": "2",
        "ut": "8dec03ba335b81bf4ebdf7b29ec27d15",
        "fields": "f1,f2,f3,f12,f13,f14,f298,f299,f249,f300,f330,f331,f332,f333,f334,f335,f336,f301,f152",
        "fs": f"m:{fs_map[exchange]}",
    }
    # 请求头（包含你提供的header）
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,vi;q=0.6",
        "sec-ch-ua": "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "script",
        "sec-fetch-mode": "no-cors",
        "sec-fetch-site": "same-site",
        "cookie": "qgqp_b_id=90672b8a757593658f7f51013d87539f; EMFUND1=null; EMFUND2=null; EMFUND3=null; EMFUND4=null; EMFUND5=null; EMFUND0=null; EMFUND7=05-22%2015%3A42%3A03@%23%24%u6613%u65B9%u8FBE%u521B%u4E1A%u677FETF@%23%24159915; EMFUND8=05-22%2015%3A50%3A52@%23%24%u6613%u65B9%u8FBE%u6DF1%u8BC1100ETF@%23%24159901; EMFUND9=06-17%2006%3A44%3A57@%23%24%u535A%u65F6%u6052%u751F%u79D1%u6280ETF%28QDII%29@%23%24159742; EMFUND6=06-17 10:25:10@#$%u5BCC%u56FD%u56FD%u8BC1%u4FE1%u606F%u6280%u672F%u521B%u65B0%u4E3B%u9898ETF@%23%24159538; HAList=ty-116-00700-%u817E%u8BAF%u63A7%u80A1%2Cty-0-159707-%u5730%u4EA7ETF%2Cty-10-10009318-50ETF%u6CBD12%u67083000%2Cty-10-10008557-50ETF%u6CBD6%u67082850%2Cty-10-10009226-50ETF%u6CBD12%u67082500%2Cty-10-10008927-%u79D1%u521B50%u8D2D6%u67081400%2Cty-0-399975-%u8BC1%u5238%u516C%u53F8%2Cty-0-300124-%u6C47%u5DDD%u6280%u672F%2Cty-1-513730-%u4E1C%u5357%u4E9A%u79D1%u6280ETF; fullscreengg=1; fullscreengg2=1; st_si=10427026054834; st_asi=delete; st_pvi=86243391791039; st_sp=2023-10-28%2013%3A48%3A06; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=2; st_psi=20250625172010955-113300301090-7799223093",
        "Referer": "https://data.eastmoney.com/other/valueAnal.html",
        "Referrer-Policy": "unsafe-url"
    }

    temp_df = fetch_paginated_data(url, params,headers)

    # temp_df.columns = [
    #     "-",
    #     "-",
    #     "最新价",
    #     "-",
    #     "期权代码",
    #     "-",
    #     "期权名称",
    #     "-",
    #     "隐含波动率",
    #     "时间价值",
    #     "内在价值",
    #     "理论价格",
    #     "到期日",
    #     "-",
    #     "-",
    #     "-",
    #     "标的名称",
    #     "标的最新价",
    #     "-",
    #     "标的近一年波动率",
    # ]
    # temp_df = temp_df[
    #     [
    #         "期权代码",
    #         "期权名称",
    #         "最新价",
    #         "时间价值",
    #         "内在价值",
    #         "隐含波动率",
    #         "理论价格",
    #         "标的名称",
    #         "标的最新价",
    #         "标的近一年波动率",
    #         "到期日",
    #     ]
    # ]
    # temp_df["最新价"] = pd.to_numeric(temp_df["最新价"], errors="coerce")
    # temp_df["时间价值"] = pd.to_numeric(temp_df["时间价值"], errors="coerce")
    # temp_df["内在价值"] = pd.to_numeric(temp_df["内在价值"], errors="coerce")
    # temp_df["隐含波动率"] = pd.to_numeric(temp_df["隐含波动率"], errors="coerce")
    # temp_df["理论价格"] = pd.to_numeric(temp_df["理论价格"], errors="coerce")
    # temp_df["标的最新价"] = pd.to_numeric(temp_df["标的最新价"], errors="coerce")
    # temp_df["标的近一年波动率"] = pd.to_numeric(
    #     temp_df["标的近一年波动率"], errors="coerce"
    # )
    # temp_df["到期日"] = pd.to_datetime(
    #     temp_df["到期日"].astype(str), errors="coerce"
    # ).dt.date
    return temp_df


if __name__ == "__main__":
    # 分别获取两个交易所的数据
    df_sse = option_value_analysis_em("SSE")
    time.sleep(1)  # 防止请求过快
    df_szse = option_value_analysis_em("SZSE")

    # 添加交易所标识列以便区分
    df_sse['exchange'] = 'SSE'
    df_szse['exchange'] = 'SZSE'

    # 纵向合并两个DataFrame
    combined_df = pd.concat([df_sse, df_szse], ignore_index=True)

    # 查看合并结果
    print(combined_df.shape)
    print(combined_df['exchange'].value_counts())